package com.anche.demo.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @ClassName: HttpDistribute
 * @Description: TODO
 * @date: 2023/1/28 15:19
 * @Auther: hey
 */
@Slf4j
public class HttpDistribute {
    /**
     * 分发get请求并返回对应值
     * @param paramMap
     * @return
     */
    public static String distributionByGet(Map<String, Object> paramMap, String domain) throws Exception {
        HttpServletRequest requesParam = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String servletPath = requesParam.getServletPath();
        domain=domain+servletPath;
        paramMap.put("name","1212");
        paramMap.put("_w_signature","232");
        String result="";
        if(!paramMap.isEmpty()){
            StringBuilder sb = new StringBuilder();
            int current = 0;
            for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                current++;
                sb.append(param.getKey()).append("=").append( param.getValue());
                if (current < paramMap.entrySet().size()) {
                    sb.append("&");
                }
            }
            domain = domain + "?" + sb;
        }
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .addHeader("Accept-Encoding", "gzip, deflate")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Accept", "/")
                    .addHeader("Cookie", "add cookies here")
                    .addHeader("token", "myToken")
                    .url(domain)
                    .build();
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            result = responseBody;
        }catch (Exception e){
            log.error("转发请求失败",e);
        }
        return result;
    }
}
